package com.linciping.plugin.writer;

import com.intellij.codeInsight.actions.ReformatCodeProcessor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import org.jetbrains.kotlin.psi.*;

public class CodeInsertWriter implements Runnable {

    private Project project;
    private KtClass ktClass;
    private KtPsiFactory ktPsiFactory;

    public CodeInsertWriter(Project project, KtClass ktClass) {
        this.project = project;
        this.ktClass = ktClass;
        ktPsiFactory = KtPsiFactoryKt.KtPsiFactory(project, true);
    }

    @Override
    public void run() {
        KtObjectDeclaration ktObjectDeclaration = ktPsiFactory.createCompanionObject();
        KtClassBody objectBody = ktObjectDeclaration.getBody();
        if (objectBody != null) {
            PsiElement firstElement = objectBody.getFirstChild();
            PsiElement nameProperty = objectBody.addAfter(ktPsiFactory.createProperty("const val NAME=\"name\"\n"), firstElement);
            PsiElement ageProperty = objectBody.addAfter(ktPsiFactory.createProperty("const val AGE=\"age\"\n"), nameProperty);
            KtNamedFunction ktNamedFunction = ktPsiFactory.createFunction("fun newInstance():Sample{}");
            KtBlockExpression ktBlockExpression = ktNamedFunction.getBodyBlockExpression();
            if (ktBlockExpression != null) {
                PsiElement firstFunctionElement = ktBlockExpression.getFirstChild();
                ktBlockExpression.addAfter(ktPsiFactory.createExpression("return Sample()"), firstFunctionElement);
                objectBody.addAfter(ktNamedFunction, ageProperty);
            }
            KtClassBody ktClassBody=ktClass.getBody();
            if (ktClassBody!=null){
                PsiElement firstElement1 = ktClassBody.getFirstChild();
                ktClassBody.addAfter(ktObjectDeclaration,firstElement1);
            }
        }
        new ReformatCodeProcessor(project, ktClass.getContainingFile(), null, false).runWithoutProgress();
    }
}
